﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization;
using OffInvoiceExcelAddIn.FacturaeFiles;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using OffInvoiceExcelAddIn.UBLFiles;
using OffInvoiceExcelAddIn.CIIFiles;

namespace OffInvoiceExcelAddIn
{

    /// <summary>
    /// Clase que controla la carga de datos procedente de una factura XML en cualquiera de los formatos
    /// reconocidos por la aplicación en una plantilla
    /// </summary>
    class LoadController
    {
        #region ""Fields

        /// <summary>
        /// idioma de la aplicacion
        /// </summary>
        private string language;

        /// <summary>
        /// Variable de tipo string con el valor de la variable de entorno
        /// </summary>
        public string EnvironmentVariable = "";

        /// <summary>
        /// Variable de tipo string que contine el valor del directorio de las plantillas
        /// </summary>
        public string TemplatesDirectories = "";

        #endregion

        #region "Constructors"

        /// <summary>
        /// Constructor
        /// </summary>
        public LoadController()
        {
            //InvoiceCulture = CultureInfo.InstalledUICulture;
            EnvironmentVariable = System.Environment.GetEnvironmentVariable("APPDATA");
            CultureInfo cInfo = new CultureInfo(Globals.ThisAddIn.Application.LanguageSettings.get_LanguageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDUI));
            language = cInfo.Name;
            TemplatesDirectories = string.Concat(language, @"\");
        }


        #endregion

        #region "Public Methods"


        /// <summary>
        /// Método que carga una factura en formato Facturae
        /// </summary>
        /// <param name="file">Parámetro de tipo string con el path del archivo a cargar</param>
        /// <param name="corrective">Parámetro de tipo bool que indica si es una factura correctiva</param>
        /// <param name="import">Parámetro de tipo bool que indica si es una importación</param>
        /// <param name="saveOptions">Parámetro de tipo bool que indica si se muestra al usuario la opcion de guardar los cambios o no.</param>
        public void LoadFacturae(string file, bool corrective, bool import, bool saveOptions)
        {
            Worksheet activeDoc = null;
            TemplateController template = new TemplateController();
            if (!string.IsNullOrEmpty(file))
            {

                try
                {
                    // Para saber si es Facturae V3.1 ó V3.2
                    XmlDocument doc = new XmlDocument();
                    doc.PreserveWhitespace = true;
                    doc.Load(file);

                    XmlRootAttribute rootAttribute = new XmlRootAttribute();
                    rootAttribute.Namespace = doc.DocumentElement.NamespaceURI;
                    rootAttribute.IsNullable = false;

                    XmlSerializer serializer = new XmlSerializer(typeof(Facturae), rootAttribute);
                    System.IO.StreamReader r = new System.IO.StreamReader(file);
                    Facturae copia = (Facturae)serializer.Deserialize(r);
                    r.Close();


                    //if (import)
                    //{
                        template.setTemplateType(copia, corrective, saveOptions);
                    //}

                    try
                    {
                        //int rowsCount = 0;
                        //try
                        //{

                        //    activeDoc = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
                        //    //rowsCount = Globals.ThisAddIn.Application.ActiveDocument.Tables[template.t2].Rows.Count;
                        //}
                        //catch (Exception) { }

                        //if (activeDoc == null || Globals.ThisAddIn.getControlByTag(ControlList.Tag.IH_InvoiceNumber) == null || rowsCount > 3)
                        //{
                        //    template.setTemplateType(copia, corrective, saveOptions);
                        //}
                        Globals.ThisAddIn.document = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
                        Globals.ThisAddIn.edit(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet,false);
                        ValueBinder binder = new ValueBinder(copia, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet, corrective);
                        Globals.ThisAddIn.edit(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet, true);
                        if (!import)
                        {
                            ControlMessages msg = ControlMessages.getInstance();
                            MessageBox.Show(msg.getMessage(ControlMessages.Msg.InfoImportDataOK), msg.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (import)
                        {
                            throw ex;
                        }
                        ControlMessages msg = ControlMessages.getInstance();
                        if (ex.Message.Equals(msg.getMessage(ControlMessages.Msg.ErrorNotValidTemplate)) || ex.Message.Equals(msg.getMessage(ControlMessages.Msg.InfoThirdParty)))
                        {
                            try
                            {
                                DialogResult result = MessageBox.Show(ex.Message, msg.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                                if (result.Equals(DialogResult.Yes))
                                {
                                    template.setTemplateType(copia, corrective, false);
                                    Globals.ThisAddIn.edit(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet, false);
                                    ValueBinder binder = new ValueBinder(copia, Globals.ThisAddIn.Application.ActiveSheet, corrective);
                                    Globals.ThisAddIn.edit(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet, true);
                                }
                            }
                            catch (Exception exs) { throw exs; }
                        }
                        else
                            MessageBox.Show(msg.getMessage(ControlMessages.Msg.ErrorLoadInvoiceXML), msg.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    }


                }
                catch (Exception ex)
                {
                    if (import)
                    {
                        throw ex;
                    }
                    ControlMessages controlM = ControlMessages.getInstance();
                    MessageBox.Show(controlM.getMessage(ControlMessages.Msg.ErrorSchema), controlM.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
            }
        }

        /// <summary>
        /// Método que carga una factura en formato UBL
        /// </summary>
        /// <param name="file">Parámetro de tipo string con el path del archivo a cargar</param>
        /// <param name="corrective">Parámetro de tipo bool que indica si es una factura correctiva</param>
        /// <param name="import">Parámetro de tipo bool que indica si es una importación</param>
        /// <param name="saveOptions">Parámetro de tipo bool que indica si se muestra al usuario la opcion de guardar los cambios o no.</param>
        public void LoadUBL(string file, bool import, bool corrective, bool saveOptions)
        {

            //Worksheet activeDoc = null;
            Language labels = Language.getInstance();
            TemplateController templateC = new TemplateController();
            if (!string.IsNullOrEmpty(file))
            {

                try
                {

                    XmlSerializer serializer = new XmlSerializer(typeof(Invoice));
                    System.IO.StreamReader r = new System.IO.StreamReader(file);
                    Invoice copia = (Invoice)serializer.Deserialize(r);
                    r.Close();

                    //if (import)
                    //{
                        string template = EnvironmentVariable + Paths.TemplatePath + TemplatesDirectories;

                        if (!corrective)
                        {
                            if (copia.AccountingSupplierParty.Party.PartyIdentification.ID.ToLower().Equals(copia.Signature.SignatoryParty.PartyIdentification.ID.ToLower()))
                            {
                                if (copia.InvoiceTypeCode.ToLower().Equals("Rectificativa".ToLower()))
                                {
                                    template += labels.getLabels("CorrectiveTemplate")+".xltx";
                                }
                                else
                                {
                                    template += labels.getLabels("BasicTemplate")+".xltx";
                                }
                            }
                            else
                            {

                                if (copia.InvoiceTypeCode.ToLower().Equals("Rectificativa".ToLower()))
                                {
                                    template += labels.getLabels("CorrectiveAndThirdTemplate")+".xltx";
                                }
                                else
                                {
                                    template += labels.getLabels("ThirdTemplate")+".xltx";
                                }
                            }
                        }
                        else 
                        {
                            template += labels.getLabels("CorrectiveTemplate")+".xltx";
                        }

                        object temp = template;
                        templateC.LoadInvoiceTemplate(temp, saveOptions);
                    //}

                    try
                    {
                        ////int rowsCount = 0;
                        ////try
                        ////{

                        ////    activeDoc = Globals.ThisAddIn.Application.ActiveSheet;
                        ////    //rowsCount = Globals.ThisAddIn.Application.ActiveDocument.Tables[templateC.t2].Rows.Count;
                        ////}
                        ////catch (Exception) { }

                        ////if (activeDoc == null || Globals.ThisAddIn.getControlByTag(ControlList.Tag.IH_InvoiceNumber) == null || rowsCount > 3)
                        ////{
                        //    string template = EnvironmentVariable + Paths.TemplatePath + TemplatesDirectories;

                        //    if (copia.AccountingSupplierParty.Party.PartyIdentification.ID.ToLower().Equals(copia.Signature.SignatoryParty.PartyIdentification.ID.ToLower()))
                        //    {
                        //        if (copia.InvoiceTypeCode.ToLower().Equals("Rectificativa".ToLower()))
                        //        {
                        //            template += "RectificativaBasica.xltx";
                        //        }
                        //        else
                        //        {
                        //            template += "FacturaeBasica.xltx";
                        //        }
                        //    }
                        //    else
                        //    {

                        //        if (copia.InvoiceTypeCode.ToLower().Equals("Rectificativa".ToLower()))
                        //        {
                        //            template += "Rectificativa_por_tercero.xltx";
                        //        }
                        //        else
                        //        {
                        //            template += "Emitida_por_Tercero.xltx";
                        //        }
                        //    }
                        //    object temp = template;
                        //    templateC.LoadInvoiceTemplate(temp, true);
                        //}
                        Globals.ThisAddIn.document = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
                        Globals.ThisAddIn.edit(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet, false);
                        UBLGenerator ubl = new UBLGenerator();
                        ubl.Invoice = copia;
                        ubl.loadData();
                        Globals.ThisAddIn.edit(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet, true);

                        if (!import)
                        {
                            ControlMessages msg = ControlMessages.getInstance();
                            MessageBox.Show(msg.getMessage(ControlMessages.Msg.InfoImportDataOK), msg.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        }
                    }
                    catch (Exception)
                    {
                        ControlMessages msg = ControlMessages.getInstance();
                        MessageBox.Show(msg.getMessage(ControlMessages.Msg.ErrorLoadInvoiceXML), msg.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    }


                }
                catch (Exception ex)
                {
                    if (import)
                    {
                        throw ex;
                    }
                    ControlMessages controlM = ControlMessages.getInstance();
                    MessageBox.Show(controlM.getMessage(ControlMessages.Msg.ErrorSchema), controlM.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
            }
        }


        /// <summary>
        /// Método que carga una factura en formato CII
        /// </summary>
        /// <param name="file">Parámetro de tipo string con el path del archivo a cargar</param>
        /// <param name="corrective">Parámetro de tipo bool que indica si es una factura correctiva</param>
        /// <param name="import">Parámetro de tipo bool que indica si es una importación</param>
        /// <param name="saveOptions">Parámetro de tipo bool que indica si se muestra al usuario la opcion de guardar los cambios o no.</param>
        public void LoadCII(string file, bool import, bool corrective, bool saveOptions)
        {

            //Worksheet activeDoc = null;
            Language labels = Language.getInstance();
            TemplateController templateC = new TemplateController();
            if (!string.IsNullOrEmpty(file))
            {

                try
                {

                    XmlSerializer serializer = new XmlSerializer(typeof(CrossIndustryInvoice));
                    System.IO.StreamReader r = new System.IO.StreamReader(file);
                    CrossIndustryInvoice copia = (CrossIndustryInvoice)serializer.Deserialize(r);
                    r.Close();

                    //if (import)
                    //{
                        string template = EnvironmentVariable + Paths.TemplatePath + TemplatesDirectories;

                        if (!corrective)
                        {
                            //if (copia.AccountingSupplierParty.Party.PartyIdentification.ID.ToLower().Equals(copia.Signature.SignatoryParty.PartyIdentification.ID.ToLower()))
                            //{
                            if (copia.CIIHExchangedDocument.TypeCode.Equals("82"))
                            {
                                template += labels.getLabels("CorrectiveTemplate")+".xltx";
                            }
                            else
                            {
                                template += labels.getLabels("BasicTemplate")+".xltx";
                            }
                            //}
                            //else
                            //{

                            //    if (copia.InvoiceTypeCode.ToLower().Equals("Rectificativa".ToLower()))
                            //    {
                            //        template += "Rectificativa_por_tercero.xltx";
                            //    }
                            //    else
                            //    {
                            //        template += "Emitida_por_Tercero.xltx";
                            //    }
                            //}
                        }
                        else 
                        {
                            template += labels.getLabels("CorrectiveTemplate")+".xltx";
                        }
                        object temp = template;
                        templateC.LoadInvoiceTemplate(temp, saveOptions);
                    //}

                    try
                    {
                        //int rowsCount = 0;
                        //try
                        //{

                        //    activeDoc = Globals.ThisAddIn.Application.ActiveSheet;
                        //    //rowsCount = Globals.ThisAddIn.Application.ActiveDocument.Tables[templateC.t2].Rows.Count;
                        //}
                        //catch (Exception) { }

                        //if (activeDoc == null || Globals.ThisAddIn.getControlByTag(ControlList.Tag.IH_InvoiceNumber) == null || rowsCount > 3)
                        //{
                        //    string template = EnvironmentVariable + Paths.TemplatePath + TemplatesDirectories;

                        //    //if (copia.AccountingSupplierParty.Party.PartyIdentification.ID.ToLower().Equals(copia.Signature.SignatoryParty.PartyIdentification.ID.ToLower()))
                        //    //{
                        //    if (copia.CIIHExchangedDocument.TypeCode.Equals("82"))
                        //    {
                        //        template += "RectificativaBasica.xltx";
                        //    }
                        //    else
                        //    {
                        //        template += "FacturaeBasica.xltx";
                        //    }
                        //    //}
                        //    //else
                        //    //{

                        //    //    if (copia.InvoiceTypeCode.ToLower().Equals("Rectificativa".ToLower()))
                        //    //    {
                        //    //        template += "Rectificativa_por_tercero.xltx";
                        //    //    }
                        //    //    else
                        //    //    {
                        //    //        template += "Emitida_por_Tercero.xltx";
                        //    //    }
                        //    //}

                        //    object temp = template;
                        //    templateC.LoadInvoiceTemplate(temp, true);
                        //}
                        Globals.ThisAddIn.document = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
                        Globals.ThisAddIn.edit(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet, false);
                        CIIGenerator cii = new CIIGenerator();
                        cii.Invoice = copia;
                        cii.loadData();

                        Globals.ThisAddIn.edit(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet, true);

                        if (!import)
                        {
                            ControlMessages msg = ControlMessages.getInstance();
                            MessageBox.Show(msg.getMessage(ControlMessages.Msg.InfoImportDataOK), msg.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        }
                    }
                    catch (Exception)
                    {
                        ControlMessages msg = ControlMessages.getInstance();
                        MessageBox.Show(msg.getMessage(ControlMessages.Msg.ErrorLoadInvoiceXML), msg.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    }


                }
                catch (Exception ex)
                {
                    if (import)
                    {
                        throw ex;
                    }
                    ControlMessages controlM = ControlMessages.getInstance();
                    MessageBox.Show(controlM.getMessage(ControlMessages.Msg.ErrorSchema), controlM.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
            }
        }

        #endregion

    }
}
